package com.woniu.inteceptor;

import com.woniu.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        System.out.println("当前请求的路径是：" + uri);

        if (uri.equals("/doc.html")) {
            return true;
        }

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        // 这句话，一定不能少，否则会有跨域问题
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // 得到请求头中的token
        String token = request.getHeader("authentication");
        System.out.println("前端访问时带过来的token:" + token);

        if (token == null) {
            // 没有token, 说明没有登录
            token = request.getParameter("token");
            if (token == null) {
                throw new RuntimeException("请先登录！");
            } else {
                return true;
            }
        } else {
            try {
                jwtUtil.parseToken(token);
                return true;
            } catch (ExpiredJwtException e) {
                e.printStackTrace();
                // response.getWriter().print("token expired!");
                throw new ExpiredJwtException(null, null, "对不起,token过期了！", e);
            } catch (SignatureException e) {
                // response.getWriter().print("token error!");
                throw new SignatureException("token 错误！", e);
            } catch (RuntimeException e) {
                // response.getWriter().print("token parse error!");
                throw new RuntimeException("token解析有误!", e);
            }
        }
    }
}
